package enterprise.web_jpa_war.servlet;

import java.io.*;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import javax.persistence.PersistenceUnit;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;

@WebServlet(name="ListCustomerServlet", urlPatterns={"/ListCustomer.do"})
public class ListCustomerServlet extends HttpServlet {
    
    @PersistenceUnit
    private EntityManagerFactory emf;
   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        assert emf != null;                //Make sure injection went through correctly.
        EntityManager em = null;
        try {
            em = emf.createEntityManager();

            //query for all the persons in database
            List customers = em.createQuery("select p from Customer p").getResultList();
            if(customers.isEmpty()){
               request.setAttribute("message","There is no Customers in the database");
               request.getRequestDispatcher("message.jsp").forward(request, response);
            }
            request.setAttribute("customerList",customers);

            //Forward to the jsp page for rendering
           request.getRequestDispatcher("viewcustomer.jsp").forward(request, response);
        } catch (Exception ex) {
            throw new ServletException(ex);
        } finally {
            //close the em to release any resources held up by the persistebce provider
            if(em != null) {
                em.close();
            }
        }
    } 
   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }


    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
